package com.xm.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;


/**
 * 解密
 * @author 康文程
 * @date 2023-1-5 下午 03:06
 */
public class DecryptExampleUtil {

    private static final String ALGORITHM = "AES";
    private static final String KEY = "abcdefghijklmnop";

    /**
     * 解密
     *
     * @param encodedText 加密后的字符串
     * @return 解密后的字符串
     * @throws Exception 抛出错误
     */
    public static String decrypt(String encodedText) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] decodedBytes = Base64.getDecoder().decode(encodedText);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }
    /**
     * 加密
     *
     * @param plainText 明文字符串
     * @return 加密后的字符串
     * @throws Exception 抛出错误
     */
    public static String encrypt(String plainText) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 使用方法
     * @param args 数组
     * @throws Exception 抛出错误
     */
    public static void main(String[] args) throws Exception {
        String plainText = "Hello, world!";
        String encryptedText = encrypt(plainText);
        System.out.println("加密结果：" + encryptedText);
        String decryptedText = decrypt(encryptedText);
        System.out.println("解密结果：" + decryptedText);
    }
}
